// import UQRCode from '@uqrcode/js';
import request from './request';
// 引入SDK核心类
// import QQMapWX from "@/static/js/qqMapSdk/qqmap-wx-jssdk.min.js";
// 实例化API核心类
// const qqmapsdk = new QQMapWX({
//   key: "BMFBZ-WMZCG-UOAQK-QIITR-PQAFE-5OBRQ", // 必填
// });
const wx = uni;
const utils = {
  // openid
  openId: '',
  // 客服电话
  telephone: '',
  // 请求baseurl
  baseUrl: import.meta.env.VITE_BASE_URL,
  // 获取账户信息
  accountInfo: uni.getAccountInfoSync(),
  // 腾讯地图key
  locationKey: 'P2BBZ-UQJCJ-TKWFV-X6IT4-XQQ4K-7SBQL',
  /**
   * 设备信息
   */
  windowInfo: {} as any,
  /**
   * 设备顶部黑边
   */
  windowTop: 0,
  /**
   * 设备底部黑边
   */
  windowBottom: 0,
  /**
   * 获取小程序启动时的参数
   */
  launchOptionsSync: {},
  /**
   * 预览图片
   * @param url 图片连接
   */
  previewImage: (obj: any) => {
    obj.urls = obj.urls.map((v: any) => {
      v = v.replace('https', 'http');
      return v;
    });
    obj.current
      ? (obj.current = obj.current.replace('https', 'http'))
      : obj.urls[0];
    uni.previewImage({
      current: '', // 当前显示图片的http链接
      showmenu: true,
      ...obj,
    });
  },

  /**
   * 给字符串修改某个字符
   */
  getNewStr(
    str: string,
    oldStr: string = `src="/upload`,
    newStr: string = `src="${utils.baseUrl}/upload`
  ) {
    if (str) {
      /**
       * 视频处理
       */
      let srcReg = /(?<=(source[^>]src="))[^"]*/g;
      let videoList = str.match(srcReg) || [];
      if (videoList.length > 0) {
        let videoStr = str;
        videoList.forEach((v: any, i: number) => {
          videoStr = videoStr.replace(`poster=""`, `src="${v}"`);
          videoStr = videoStr.replace(`<video`, `<video style="width:100%"`);
        });
        str = videoStr;
      }
      return str.replace(new RegExp(oldStr, 'g'), newStr);
    }
  },
  /**
   * 随机字符串生成
   */
  getRandom(len: number = 32) {
    var str = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    var result = '';
    for (var i = len; i > 0; --i)
      result += str[Math.floor(Math.random() * str.length)];
    return result;
  },
  /**
   * 手机号码显示星号
   */
  maskContact(phone: string) {
    // if (typeof phone == "number") phone.toString();
    return phone && typeof phone == 'string'
      ? phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2')
      : '--';
  },
  /**
   * 设置页面标题
   * @param title 标题
   */
  setPageTitle: (title: string) => {
    uni.setNavigationBarTitle({
      title,
    });
  },
  /**
   * 设置千分号和保留两位小数
   */
  ThousandAndDecimal: (num: number, digit: number = 2, unit: string = '') => {
    const number = Number(num);
    if (isNaN(number)) return num;
    if (number) {
      return digit > 0
        ? number.toFixed(digit).replace(/(\d)(?=(\d{3})+\.)/g, '$1,') + unit
        : number
            .toFixed(2)
            .replace(/(\d)(?=(\d{3})+\.)/g, '$1,')
            .split('.')[0] + unit;
    } else {
      return '0.00' + unit;
    }
  },

  /**
   * 是否手机号
   */
  isMobilePhone: (phone: string) => {
    if (phone) return /^1[3-9]\d{9}$/.test(phone);
  },
  /**
   * 打电话
   * @param number 手机号
   */
  makePhoneCall: (number?: string | number) => {
    wx.makePhoneCall({
      phoneNumber: number ? number.toString() : utils.telephone, //仅为示例，并非真实的电话号码
    });
  },
  // 报错模态弹窗
  showErr: (text?: string, fn?: Function) => {
    wx.showModal({
      title: '提示',
      content: text || '出错了，请稍后重试！',
      showCancel: false,
      confirmColor: '#3974f6',
      success: () => {
        fn && fn();
      },
    });
  },
  // 模态弹窗
  showModal: (
    fn: Function,
    text: string = '出错了，请稍后重试',
    obj: any = {}
  ) => {
    wx.showModal({
      title: '提示',
      content: text || '出错了，请稍后重试！',
      confirmColor: '#3974f6',
      ...obj,
      success: (res: any) => {
        if (res.confirm) {
          fn();
        }
      },
    });
  },
  // 提示弹窗
  showToast: (err?: string) => {
    wx.showToast({
      title: err || '出错了！',
      icon: 'none',
      duration: 2000,
    });
  },
  // 隐藏加载框
  hideLoading: () => {
    wx.hideLoading();
  },
  // 显示加载框
  showLoading: (v?: string) => {
    wx.showLoading({
      title: v || '加载中',
      mask: true,
    });
  },
  /**
   * 缓存数据
   */
  setStorage: (key: any, value: any) => {
    wx.setStorageSync(key, value);
  },
  /**
   * 获取缓存数据
   */
  getStorage: (key: any) => {
    return wx.getStorageSync(key);
  },
  /**
   * 删除缓存数据
   */
  removeStorage: (key: any) => {
    return wx.removeStorageSync(key);
  },
  /**
   * 关闭当前页面跳转
   * @param url 目标页面
   */
  redirectTo: (url: string) => {
    wx.redirectTo({
      url: '/pages/' + url,
    });
  },
  /**
   * 关闭所有页面跳转
   * @param url 目标页面
   */
  reLaunch: (url: string) => {
    wx.reLaunch({
      url: '/pages/' + url,
    });
  },
  /**
   * 保存当前页面跳转
   * @param url 目标页面
   */
  navigateTo: (url: string) => {
    wx.navigateTo({
      url: '/pages/' + url,
    });
  },
  /**
   * 关闭页面
   */
  navigateBack: (res?: any) => {
    if (res) {
      if (res.success) {
        wx.showToast({
          title: res.msg || '出错了！',
          icon: 'none',
          duration: 1500,
        });
        setTimeout(() => {
          uni.navigateBack({
            delta: 1,
          });
        }, 1000);
      }
    } else {
      uni.navigateBack({
        delta: 1,
      });
    }
  },
  /**
   * 时间格式转换
   * @param date 时间
   * @returns
   */
  formatDate: (date: string) => {
    return date ? new Date(date).toLocaleString() : '';
  },
  /**
   *
   * @param id canvasId
   * @param fn 回调方法
   */
  // UQRcodeFn: async (id: string, fn: any) => {
  //   utils.showLoading();
  //   // 获取uQRCode实例
  //   var qr = new UQRCode();
  //   // 设置二维码内容
  //   qr.data =
  //     'MECARD:N:小冯;TEL:18888888888;EMAIL:xiaofeng@email.com;ADR:铭泰大厦;ORG:研发部;';
  //   // 设置二维码大小，必须与canvas设置的宽高一致
  //   qr.size = 200;
  //   qr.margin = 10;
  //   // 调用制作二维码方法
  //   qr.make();
  //   // 获取canvas上下文
  //   var canvasContext = uni.createCanvasContext(id, this); // 如果是组件，this必须传入
  //   // 设置uQRCode实例的canvas上下文
  //   qr.canvasContext = canvasContext;
  //   // 调用绘制方法将二维码图案绘制到canvas上
  //   qr.drawCanvas();
  //   setTimeout(() => {
  //     uni.canvasToTempFilePath(
  //       {
  //         canvasId: id,
  //         success: (res) => {
  //           fn(res);
  //         },
  //         fail: (err) => {
  //           utils.showErr(err.errMsg);
  //         },
  //         complete: () => {
  //           utils.hideLoading();
  //         },
  //       }
  //       // this // 组件内使用必传当前实例
  //     );
  //   }, 300);
  // },
  /**
   * 文件上传
   * @param filePath 文件参数
   * @param fn 回调
   */
  uploadFile: (filePath: any, fn: any) => {
    wx.uploadFile({
      url: import.meta.env.VITE_BASE_URL + '/api/common/fileUpload', //仅为示例，非真实的接口地址
      filePath,
      name: 'file',
      success(res) {
        if (res.data) {
          const data = res.data;
          fn(JSON.parse(data));
        }
      },
      fail(err) {
        console.log(err, 'err----------');
      },
    });
  },
  /**
   * 业务附件上传
   * @param filePath 文件参数
   * @param businessId 业务id
   * @param fn 回调
   */
  uploadBusinessFile: (filePath: any, formData: any, fn: any) => {
    wx.uploadFile({
      url: import.meta.env.VITE_BASE_URL + '/api/common/uploadBusinessFile', //仅为示例，非真实的接口地址
      filePath,
      name: 'file',
      formData,
      success(res) {
        if (res.data) {
          const data = res.data;
          fn(JSON.parse(data));
        }
      },
      fail: (err) => {
        utils.showErr(err ? JSON.stringify(err) : '出错了，请稍后重试！');
      },
      complete() {
        utils.hideLoading();
      },
    });
  },
  openDocument: (url: string) => {
    wx.showLoading({
      title: '文件打开中',
      mask: true,
    });
    wx.downloadFile({
      // 示例 url，并非真实存在
      url,
      success: function (res) {
        const filePath = res.tempFilePath;
        wx.openDocument({
          filePath: filePath,
          success: function (res) {
            // console.log(res);
          },
          fail: (err) => {
            wx.showModal({
              title: '提示',
              content: JSON.stringify(err) || '出错了，请稍后重试！',
              showCancel: false,
            });
          },
        });
      },
      fail: (err) => {
        wx.showModal({
          title: '提示',
          content: err || '出错了，请稍后重试！',
          showCancel: false,
        });
      },
      complete: () => {
        wx.hideLoading();
      },
    });
  },
  /**
   * 拆分省市区以及具体位置
   * @param {*} address
   */
  async splitAddress({
    address,
    latitude,
    longitude,
  }: {
    address: string;
    latitude: number;
    longitude: number;
  }) {
    const reg = /.+?(省|市|自治区|自治州|县|区)/g;
    let list: any = address.match(reg);

    if (!list || list.length == 0) {
      const location: any = await utils.getLocationByLngAndLat(
        latitude,
        longitude
      );
      list = [];
      list[0] = location.province;
      list[1] = location.city;
      list[2] = location.district;
    }
    const province = list[0];
    const city =
      list && list.length == 2 ? list[0] : list.length == 3 ? list[1] : '';
    const area =
      list && list.length == 2 ? list[1] : list.length == 3 ? list[2] : '';
    const detail = address.substring(
      province.length + city.length + area.length
    );
    return {
      province,
      city,
      area,
      detail,
    };
  },
  /**
   * 通过经纬度逆地址解析
   * @param latitude
   * @param longitude
   * @returns 返回地址信息
   */
  getLocationByLngAndLat(latitude: number, longitude: number) {
    // return new Promise<void>((resolve, reject) => {
    //   qqmapsdk.reverseGeocoder({
    //     location: {
    //       longitude,
    //       latitude,
    //     },
    //     success: (res: any) => {
    //       if (res.result && res.result.address_component) {
    //         resolve(res.result.address_component);
    //       }
    //     },
    //     fail: (err: any) => {
    //       reject(err);
    //     },
    //   });
    // });
  },

  /**
   * 微信支付
   * @param prepayId  微信支付id
   * @param fn 回调
   */
  WXpay: async (prepayId: string, fn: Function) => {
    // const timeStamp = String(Date.now());
    // const nonceStr = utils.getRandom();
    // const res: any = await wxAppletPaySign({
    //   timeStamp,
    //   nonceStr,
    //   appId: utils.accountInfo.miniProgram.appId || 'wx83623a011f5431e9',
    //   prepayId,
    // });
    // if (res.success) {
    //   utils.showLoading();
    //   uni.requestPayment({
    //     timeStamp,
    //     nonceStr,
    //     package: prepayId,
    //     signType: 'RSA	',
    //     paySign: res.data,
    //     success(res: any) {
    //       fn(res);
    //     },
    //     fail(err: any) {
    //       utils.showErr('支付失败');
    //     },
    //     complete() {
    //       utils.hideLoading();
    //     },
    //   } as any);
    // }
  },
  /**
   * 获取订单状态
   */
  getOrderStatus(state: string) {
    let text = '';
    if (state === 'Z') {
      text = '暂存';
    } else if (state === 'A') {
      text = '创建';
    } else if (state === 'B') {
      text = '审核中';
    } else if (state === 'C') {
      text = '已审核';
    } else if (state === 'D') {
      text = '重新审核';
    } else {
      text = '未知状态'; // 处理未知状态
    }
    return text;
  },
} as any;

export default utils;
